package com.dyz.LeetCodeforSwordFingerOffer;

/**
 * @author: daiyizheng
 * @date: 2021/7/3 18:35
 * @description:
 */
public class ReverseWords58 {
    public static void main(String[] args) {
        new ReverseWords58().reverseWords("a good   example");
    }

    public String reverseWords(String s) {
        //暴力求解
        if (s==null||s.length()==0){return s;}
        String [] ans = s.split(" ");
        String res = "";
        for(int i=ans.length-1;i>=0;i--){
            //不保留多余空格
            if(ans[i].trim().length()>0) {
                res = res + ans[i].trim() + " ";
            }
        }
        return res.trim();
    }
    public String reverseWords1(String s) {
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) != ' ') {i--;} // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') {i--;} // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }
}
